//
//  CountDownManager.m
//  yjw-winner
//
//  Created by 隆霁 on 2018/9/27.
//  Copyright © 2018年 Shanghai decade financial information service co., LTD. All rights reserved.
//

#import "CountDownManager.h"

@interface CountDownManager () {
    NSTimer *_timer;
}
@property (nonatomic, copy) CountDownManagerCallBackBlock block;
@end
static CountDownManager *_manager = nil;
@implementation CountDownManager

+ (CountDownManager *)manager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[CountDownManager alloc] init];
    });
    return _manager;
}
- (instancetype)init {
    if (self = [super init]) {
        self.currentCount = 60;
    }
    return self;
}
+ (CountDownManager *)managerWithCallBack:(CountDownManagerCallBackBlock)block {
    CountDownManager *manager = [CountDownManager manager];
    [manager startWithCountDownManagerBlock:block];
    return manager;
}
- (void)startWithCountDownManagerBlock:(CountDownManagerCallBackBlock)block {
    self.block = block;
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(countDownWith:) userInfo:_timer repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode: NSRunLoopCommonModes];
    }else {
        [_timer fire];
    }
}

- (void)countDownWith:(NSTimer *)timer {
    NSLog(@"%ld", _currentCount);
    if (_currentCount > 0) {
        _currentCount -= 1;
    }else {
        _currentCount = 60;
        [_timer invalidate];
        _timer = nil;
    }
    if (self.block) {
        self.block(self.currentCount);
    }
}
@end
